package do

import (
	"micro.room.server/common"
	"micro.room.server/database"
	"micro.room.server/models"
)

const (
	RoomDeviceTable = "vs_r_device"
)

func CreateRoomDevice(device *models.VsRDevice) error {
	eg := database.GetDB()
	if eg == nil {
		return common.DBNil
	}

	afterID, err := eg.Table(RoomDeviceTable).Insert(device)
	if err != nil {
		return common.DBErr
	}
	if afterID < 1 {
		return common.DBInsertErr
	}

	return nil
}

func UpdateRoomDeviceInfo(device *models.VsRDevice) error {
	eg := database.GetDB()
	if eg == nil {
		return common.DBNil
	}

	afterID, err := eg.Table(RoomDeviceTable).ID(device.Id).Update(device)
	if err != nil {
		return common.DBErr
	}
	if afterID < 1 {
		return common.DBInsertErr
	}

	return nil
}

func DeleteRoomDevice(deviceIDs []uint64) error {
	eg := database.GetDB()
	if eg == nil {
		return common.DBNil
	}

	device := &models.VsRDevice{}
	afterID, err := eg.Table(RoomDeviceTable).In("id", deviceIDs).Delete(device)
	if err != nil {
		return common.DBErr
	}
	if afterID < 1 {
		return common.DBInsertErr
	}
	return nil
}

func SearchRoomDevice(req *models.SearchRoomDeviceParams) ([]*models.VsRDevice, int64, error) {
	eg := database.GetDB()
	if eg == nil {
		return nil, 0, common.DBNil
	}
	session := eg.NewSession()
	if session == nil {
		return nil, 0, common.DBNil
	}

	devices := make([]*models.VsRDevice, 0)
	if req.RoomNo > 0 {
		session.Where("room_no = ?", req.RoomNo)
	}
	if req.BedNum > 0 {
		session.Where("bed_num = ?", req.BedNum)
	}
	if req.PeopleNum > 0 {
		session.Where("people_num = ?", req.PeopleNum)
	}

	session.Limit(int(req.Limit), int(req.Offset))

	count, err := session.Table(RoomDeviceTable).FindAndCount(devices)
	if err != nil {
		return nil, 0, err
	}

	return devices, count, nil
}

func DeviceList(roomID uint64) ([]*models.VsRDevice, error) {
	eg := database.GetDB()
	if eg == nil {
		return nil, common.DBNil
	}

	devices := make([]*models.VsRDevice, 0)

	err := eg.Table(RoomDeviceTable).In("room_id", roomID).Find(devices)
	if err != nil {
		return nil, err
	}

	return devices, nil
}
